﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

using InfFront.InfoViews.Base;
using InfFront.UICore;

namespace InfFront.InfoViews.WPF
{
    /// <summary>
    /// Interaction logic for DataGridFrame.xaml
    /// </summary>
    public partial class DataGridFrame : BaseListWithToolbarContentFrame
    {
        #region Private Variables
        private static UICoreIImageToImageConverter imageConverter;
        #endregion

        static DataGridFrame()
        {
            imageConverter = new UICoreIImageToImageConverter();
        }

        public DataGridFrame()
        {
            InitializeComponent();
        }

        protected override void DoRebuild()
        {
            dataGrid.ItemsSource = null;
            dataGrid.Columns.Clear();

            if (Source == null)
                return;

            dataGrid.ItemsSource = Source.GetBindingSource();
        }

        protected override void DoRefresh()
        {
            dataGrid.ItemsSource = Source.GetBindingSource();
        }

        private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (IsRebuilding)
                return;

            InfoViewEntry entry = null;
            if (e.AddedItems.Count > 0)
                entry = Source.ExtractEntry(e.AddedItems[0]);
            Owner.UpdateWithNewCurrentEntry(entry);
            e.Handled = true;
        }

        private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            var field = Source.FieldByName(e.PropertyName);
            if (field == null)
                return;
            if (typeof(IImage).IsAssignableFrom(field.EffectiveDisplayType))
            {
                var imageColumn = new DataGridImageColumn();
                var binding = new Binding(field.Name);
                imageColumn.Binding = binding;
                binding.Mode = BindingMode.OneWay;
                binding.Converter = imageConverter;
                imageColumn.IsReadOnly = true;
                e.Column = imageColumn;
            }
            e.Column.Header = field.Title;
            BindingOperations.SetBinding(e.Column, DataGridColumn.WidthProperty,
                new Binding("VisualSettings.DataGridColumnWidth") { Source = field, Mode = BindingMode.TwoWay });
            BindingOperations.SetBinding(e.Column, DataGridColumn.DisplayIndexProperty,
                new Binding("Order") { Source = field, Mode = BindingMode.TwoWay });
        }

        private void dataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (CurrentEntry == null)
                return;

            var args = new InfoViewCommand.ExecutionArgs();
            args.CurrentEntry = CurrentEntry;
            Source.ExecuteListDoubleClick(args);

            e.Handled = true;
        }

        //
        // SINGLE CLICK EDITING
        //
        private void DataGridCell_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;
            if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
            {
                if (!cell.IsFocused)
                {
                    cell.Focus();
                }
                DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
                if (dataGrid != null)
                {
                    if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                    {
                        if (!cell.IsSelected)
                            cell.IsSelected = true;
                    }
                    else
                    {
                        DataGridRow row = FindVisualParent<DataGridRow>(cell);
                        if (row != null && !row.IsSelected)
                        {
                            row.IsSelected = true;
                        }
                    }
                }
            }
        }

        static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element;
            while (parent != null)
            {
                T correctlyTyped = parent as T;
                if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }

                parent = VisualTreeHelper.GetParent(parent) as UIElement;
            }
            return null;
        } 
    }
}
